package com.km.wskj.itmonitor.pager;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.km.wskj.itmonitor.LApplication;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.UpdateService;
import com.km.wskj.itmonitor.other.NoTouchViewPager;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.base.LFragment;
import com.km.wskj.itmonitor.pager.im.IMFragment;
import com.km.wskj.itmonitor.pager.loading.LoadingActivity;
import com.km.wskj.itmonitor.pager.wq.WqFragment;
import com.km.wskj.itmonitor.pager.monitor.MonitorFragment;
import com.km.wskj.itmonitor.pager.news.NewsFragment;
import com.km.wskj.itmonitor.pager.mine.SettingFragment;
import com.km.wskj.itmonitor.utils.ActivityCollector;
import com.zxl.zxlapplibrary.control.VersionControl;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.InstallApkUtil;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.toolsfinal.StringUtils;
import es.dmoral.toasty.Toasty;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageBottomTabLayout;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.item.NormalItemView;
import okhttp3.Call;

/**
 * @author by Xianling.Zhou on 2017/2/17.
 */
//新的主界面
public class MainActivity extends LActivity {
    private static final String TAG = "MainActivity";

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    private static Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            normalToasty("再按一次退出");
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            Log.e(TAG, "exit application");
            ActivityCollector.finishAll();
        }
    }

    //data
    List<LFragment> fragments = new ArrayList<>();
    NavigationController mNavigationController;


    //ui
    @BindView(R.id.tab_viewpager)
    NoTouchViewPager mViewpager;
    @BindView(R.id.pageBottomTabLayout)
    PageBottomTabLayout mTab;

    private String index;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_main);
        ButterKnife.bind(this);
        initData();

        if (getIntent() != null)
            index = getIntent().getStringExtra("index");

        checkUpdate();//自动更新
    }

    private void initData() {
        fragments.add(new WqFragment());//微栖
        fragments.add(new MonitorFragment());//监控
        fragments.add(new NewsFragment());//新闻
        fragments.add(new IMFragment());//交流
        fragments.add(new SettingFragment());//我的


        mNavigationController = mTab.custom()
                .addItem(newItem(R.mipmap.ic_wq_normal, R.mipmap.ic_wq_selected, "微栖"))
                .addItem(newItem(R.drawable.ic_monitor_normal_24dp, R.drawable.ic_monitor_selected_24dp, "监控"))
                .addItem(newItem(R.drawable.ic_news_normal_24dp, R.drawable.ic_news_selected_24dp, "新闻"))
                .addItem(newItem(R.drawable.ic_chat_normal_24dp, R.drawable.ic_chat_selected_24dp, "交流"))
                .addItem(newItem(R.drawable.ic_mine_normal_24dp, R.drawable.ic_mine_selected_24dp, "我的"))
                .build();

        mViewpager.setOffscreenPageLimit(5);//设置缓存view 的个数（实际有3个，缓存2个+正在显示的1个）
        mViewpager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), fragments));
        //登陆页面跳转到我的页面
        if (index != null && index.equals("1"))
            mViewpager.setCurrentItem(fragments.size() - 1);


        //自动适配ViewPager页面切换
        mNavigationController.setupWithViewPager(mViewpager);
    }

    //创建一个Item
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        NormalItemView normalItemView = new NormalItemView(this);
        normalItemView.initialize(drawable, checkedDrawable, text);
        normalItemView.setTextDefaultColor(Color.parseColor("#999999"));
        normalItemView.setTextCheckedColor(0xFF1496EC);
        return normalItemView;
    }


    private void checkUpdate() {
        final ProgressDialog dlg = ProgressDialog.show(context, "检查更新", "请稍后...", true);
        final VersionControl vc = LApplication.app.vc;
        if (vc.isFirUpdateAvailable()) {
            vc.requestFirVersion(vc.new FirVersionCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    dlg.dismiss();
                    LogUtils.e("request xtkj update server fail", e);
                }

                @Override
                public void onResponse(Object response, int id) {
                    dlg.dismiss();
                    if (vc.checkVersion() > 0) {
                        installUpdate();
                    }
                }
            });
        }
    }

    private void installUpdate() {
        final VersionControl vc = LApplication.app.vc;
        InstallApkUtil i = new InstallApkUtil(context, getPackageName(),
                "app.apk", vc.apkUrl, vc.must == 1);//
        if (vc.must == 1) {
            i.installFromUrl("版本更新", "检测到新版本:" + vc.versionName + "\n" + vc.updateInfo
                    + "\n需要立即更新");
        } else {
            i.installFromUrl("版本更新", "检测到新版本:" + vc.versionName + "\n" + vc.updateInfo
                    + "\n是否立即更新");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        showLoadingAndLogin();
    }

    //--管理加载和登录------------------------------------------------------
    private void showLoadingAndLogin() {
        if (pdc.loadingFlag == 0) {
            Intent t = new Intent(this, LoadingActivity.class);
            startActivity(t);
//            startActivityForResult(t, Constant.LoadingRequestCode);
        } else {
            //刷新UI
            //code here...
        }
    }
}
